package com.example.common.room

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.withContext

/**
 * 视频数据仓库
 */
class VideoRepository(private val videoFavoriteDao: VideoFavoriteDao) {
    
    /**
     * 获取所有收藏的视频
     */
    fun getAllFavoriteVideos(): Flow<List<VideoFavorite>> {
        return videoFavoriteDao.getAllFavoriteVideos()
    }
    
    /**
     * 获取所有点赞的视频
     */
    fun getAllLikedVideos(): Flow<List<VideoFavorite>> {
        return videoFavoriteDao.getAllLikedVideos()
    }
    
    /**
     * 根据视频ID查询
     */
    suspend fun getVideoById(videoId: Int): VideoFavorite? {
        return withContext(Dispatchers.IO) {
            videoFavoriteDao.getVideoById(videoId)
        }
    }
    
    /**
     * 切换点赞状态
     */
    suspend fun toggleLike(videoId: Int): Boolean {
        return withContext(Dispatchers.IO) {
            val currentStatus = videoFavoriteDao.isVideoLiked(videoId) ?: false
            val newStatus = !currentStatus
            videoFavoriteDao.updateLikeStatus(videoId, newStatus)
            newStatus
        }
    }
    
    /**
     * 切换收藏状态
     */
    suspend fun toggleFavorite(videoId: Int): Boolean {
        return withContext(Dispatchers.IO) {
            val currentStatus = videoFavoriteDao.isVideoFavorited(videoId) ?: false
            val newStatus = !currentStatus
            val currentTime = System.currentTimeMillis()
            videoFavoriteDao.updateFavoriteStatus(videoId, newStatus, currentTime)
            newStatus
        }
    }
    
    /**
     * 添加视频到数据库（如果不存在）
     */
    suspend fun addVideoIfNotExists(video: VideoFavorite) {
        withContext(Dispatchers.IO) {
            val existingVideo = videoFavoriteDao.getVideoById(video.id)
            if (existingVideo == null) {
                videoFavoriteDao.insertOrUpdate(video)
            }
        }
    }
    
    /**
     * 检查视频是否已点赞
     */
    suspend fun isVideoLiked(videoId: Int): Boolean {
        return withContext(Dispatchers.IO) {
            videoFavoriteDao.isVideoLiked(videoId) ?: false
        }
    }
    
    /**
     * 检查视频是否已收藏
     */
    suspend fun isVideoFavorited(videoId: Int): Boolean {
        return withContext(Dispatchers.IO) {
            videoFavoriteDao.isVideoFavorited(videoId) ?: false
        }
    }
    
    /**
     * 删除视频
     */
    suspend fun deleteVideo(videoId: Int) {
        withContext(Dispatchers.IO) {
            videoFavoriteDao.deleteById(videoId)
        }
    }
}